package com.dudy.authdemo.controller;

import com.alibaba.fastjson.JSONObject;
import com.dudy.authdemo.model.Person;
import com.dudy.authdemo.model.PersonRole;
import com.dudy.authdemo.service.PersonRoleService;
import com.dudy.authdemo.service.PersonService;
import com.dudy.authdemo.vo.PersonVO;
import com.dudy.common.base.CommonResponse;
import com.dudy.common.base.PageData;
import com.dudy.common.base.ResultCode;
import com.dudy.common.util.CommonUtil;
import com.dudy.common.util.DingTalkUtil;
import com.dudy.common.util.ResponseUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.parameters.P;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * @program: auth_demo
 * @author: dudy
 * @create: 2020-12-24 10:43
 * @description:
 **/
@RestController
@RequestMapping("/person")
public class PersonController {

    private static final Logger log = LoggerFactory.getLogger(PersonController.class);

    @Autowired
    private PersonService personService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private PersonRoleService personRoleService;

    @PostMapping("/addPerson")
    public CommonResponse<PersonVO> addPerson(PersonVO personVO) {
        if (personVO == null) {
            return ResponseUtils.getResponse(ResultCode.REQUEST_PARAM_NULL);
        }
        Person person = new Person();
        BeanUtils.copyProperties(personVO, person);
        person.setCreator(((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
        person.setUpdater(((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
        person.setGmtCreateTime(new Date());
        person.setGmtUpdateTime(new Date());
        person.setDeleteFlag((byte) 0);
        person.setStatus((byte) 0);
        String uuid = CommonUtil.getUuid();
        person.setSalt(uuid);
        person.setPassword(passwordEncoder.encode(personVO.getPassword() + "_" + uuid));
        try {
            int insert = personService.insert(person);
            if (StringUtils.isNotBlank(personVO.getRoles())) {
                String[] split = personVO.getRoles().split(",");
                if (split.length > 0) {
                    Example example = new Example(PersonRole.class);
                    example.createCriteria().andEqualTo("personId", person.getId());
                    personRoleService.deleteByExample(example);
                    for (int i = 0; i < split.length; i++) {
                        PersonRole personRole = new PersonRole();
                        personRole.setPersonId(person.getId());
                        personRole.setRoleCode(split[i]);
                        personRoleService.insert(personRole);
                    }
                }
            }
            if (insert == 1) {
                return ResponseUtils.getResponse(ResultCode.SUCCESS);
            } else {
                return ResponseUtils.getResponse(ResultCode.FAIL.getCode(), "操作失败，请重试");
            }
        } catch (Exception e) {
            log.error("PersonController addPerson error,请求参数：{}", JSONObject.toJSONString(personVO), e);
            DingTalkUtil.pushError("auth_demo", this.getClass().getName(), "addPerson",
                    JSONObject.toJSONString(personVO)
                    , e);
            return ResponseUtils.getResponse(ResultCode.FAIL);
        }
    }

    @PostMapping("/updatePerson")
    public CommonResponse<PersonVO> updatePerson(PersonVO personVO) {
        if (personVO == null || personVO.getId() == null) {
            return ResponseUtils.getResponse(ResultCode.REQUEST_PARAM_NULL);
        }
        Person person = new Person();
        BeanUtils.copyProperties(personVO, person);
        person.setUpdater(((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
        person.setGmtUpdateTime(new Date());
        try {
            int update = personService.updateByPrimaryKey(person);
            if (StringUtils.isNotBlank(personVO.getRoles())) {
                String[] split = personVO.getRoles().split(",");
                if (split.length > 0) {
                    Example example = new Example(PersonRole.class);
                    example.createCriteria().andEqualTo("personId", personVO.getId());
                    personRoleService.deleteByExample(example);
                    for (int i = 0; i < split.length; i++) {
                        PersonRole personRole = new PersonRole();
                        personRole.setPersonId(person.getId());
                        personRole.setRoleCode(split[i]);
                        personRoleService.insert(personRole);
                    }
                }
            }
            if (update == 1) {
                return ResponseUtils.getResponse(ResultCode.SUCCESS);
            } else {
                return ResponseUtils.getResponse(ResultCode.FAIL.getCode(), "操作失败，请重试");
            }
        } catch (Exception e) {
            log.error("PersonController update error,请求参数：{}", JSONObject.toJSONString(personVO), e);
            DingTalkUtil.pushError("auth_demo", this.getClass().getName(), "update", JSONObject.toJSONString(personVO),
                    e);
            return ResponseUtils.getResponse(ResultCode.FAIL);
        }
    }

    @GetMapping("/queryPersonById")
    public CommonResponse<PersonVO> queryPersonById(@RequestParam("id") long id) {
        Person person = new Person();
        person.setId(id);
        try {
            PersonVO personVO = personService.selectByPrimaryKey(person);
            return ResponseUtils.getResponse(ResultCode.SUCCESS);
        } catch (Exception e) {
            log.error("PersonController queryPersonById error,请求参数：{}", id, e);
            DingTalkUtil.pushError("auth_demo", this.getClass().getName(), "queryPersonById", id + "",
                    e);
            return ResponseUtils.getResponse(ResultCode.FAIL);
        }
    }

    @GetMapping("/queryPersonByExample")
    public CommonResponse<List<PersonVO>> queryPersonByExample(PersonVO personVO) {
        Example example = new Example(Person.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("deleteFlag", 0);
        if (StringUtils.isNotBlank(personVO.getUsername())) {
            criteria.andLike("username", personVO.getUsername());
        }
        if (StringUtils.isNotBlank(personVO.getPhone())) {
            criteria.andEqualTo("phone", personVO.getPhone());
        }
        if (StringUtils.isNotBlank(personVO.getEmail())) {
            criteria.andEqualTo("email", personVO.getEmail());
        }
        if (StringUtils.isNotBlank(personVO.getRoles())) {
            criteria.andLike("roles", personVO.getRoles());
        }
        try {
            List<PersonVO> personVOS = personService.selectByExample(example);
            return ResponseUtils.getResponse(ResultCode.SUCCESS, personVOS);
        } catch (Exception e) {
            log.error("PersonController queryPersonByExample error,请求参数：{}", JSONObject.toJSONString(personVO), e);
            DingTalkUtil.pushError("auth_demo", this.getClass().getName(), "queryPersonByExample",
                    JSONObject.toJSONString(personVO) + "",
                    e);
            return ResponseUtils.getResponse(ResultCode.FAIL);
        }
    }

    /**
     * 精确匹配查询
     *
     * @param personVO
     * @return
     */
    @GetMapping("/queryPersonExactly")
    public CommonResponse<List<PersonVO>> queryPersonExactly(PersonVO personVO) {
        Example example = new Example(Person.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("deleteFlag", 0);
        if (StringUtils.isNotBlank(personVO.getUsername())) {
            criteria.andEqualTo("username", personVO.getUsername());
        }
        if (StringUtils.isNotBlank(personVO.getPhone())) {
            criteria.andEqualTo("phone", personVO.getPhone());
        }
        if (StringUtils.isNotBlank(personVO.getEmail())) {
            criteria.andEqualTo("email", personVO.getEmail());
        }
        if (StringUtils.isNotBlank(personVO.getRoles())) {
            criteria.andEqualTo("roles", personVO.getRoles());
        }
        try {
            List<PersonVO> personVOS = personService.selectByExample(example);
            return ResponseUtils.getResponse(ResultCode.SUCCESS, personVOS);
        } catch (Exception e) {
            log.error("PersonController queryPersonExactly error,请求参数：{}", JSONObject.toJSONString(personVO), e);
            DingTalkUtil.pushError("auth_demo", this.getClass().getName(), "queryPersonExactly",
                    JSONObject.toJSONString(personVO) + "",
                    e);
            return ResponseUtils.getResponse(ResultCode.FAIL);
        }
    }

    @GetMapping("/queryPersonPage")
    public CommonResponse<PageData<PersonVO>> queryPersonPage(PersonVO personVO) {
        Example example = new Example(Person.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("deleteFlag", 0);
        if (StringUtils.isNotBlank(personVO.getUsername())) {
            criteria.andLike("username", personVO.getUsername());
        }
        if (StringUtils.isNotBlank(personVO.getPhone())) {
            criteria.andEqualTo("phone", personVO.getPhone());
        }
        if (StringUtils.isNotBlank(personVO.getEmail())) {
            criteria.andEqualTo("email", personVO.getEmail());
        }
        if (StringUtils.isNotBlank(personVO.getRoles())) {
            criteria.andLike("roles", personVO.getRoles());
        }
        try {
            PageData<PersonVO> pageData = personService.selectPersonPage(personVO, example);
            return ResponseUtils.getResponse(ResultCode.SUCCESS, pageData);
        } catch (Exception e) {
            log.error("PersonController queryPersonPage error,请求参数：{}", JSONObject.toJSONString(personVO), e);
            DingTalkUtil.pushError("auth_demo", this.getClass().getName(), "queryPersonPage",
                    JSONObject.toJSONString(personVO) + "",
                    e);
            return ResponseUtils.getResponse(ResultCode.FAIL);
        }
    }
}
